<template>
  <div class="simple-crop-Wrap">
    <simple-crop
      :crop-params="cropParams"
      @crop="cropCallback"
      @upload="uploadCallback"
      @close="closeCallback"
    />
    <div class="avatar" ref="avatar">
      <input @change="setCropImage" type="file" accept="image/*" />
      <img v-if="imgUrl!=''" :src="imgUrl" alt />
      <i v-else :class="`iconfont icon-${icon}`"></i>
    </div>
  </div>
</template>
<script>
import SimpleCrop from "./modules/index.vue";
import { Base64, Blob } from "@/common/utils/canvasFormat";
export default {
  name: "sSimpleCrop",
  components: { SimpleCrop },
  props: {
    // 头像显示大小
    size: {
      type: String || Number,
      default: function () {
        return "";
      },
    },
    // 文件返回格式 默认 Blob
    format: {
      type: String,
      default: function () {
        return "Blob";
      },
    },
    // 默认显示图片
    src: {
      type: String,
      default: function () {
        return "";
      },
    },
    // 默认显示上传图标
    icon: {
      type: String,
      default: function () {
        return "portrait";
      },
    },
  },
  data() {
    return {
      imgUrl: "",
      cropParams: {
        src: "", // 裁剪图片地址
        visible: false,
        size: {
          //裁剪尺寸
          width: 300,
          height: 300,
        },
        borderColor: "#fff", //裁剪框边框颜色
        cropSizePercent: 0.9, //裁剪框显示比例
      },
    };
  },
  methods: {
    //监听选择图片
    setCropImage(evt) {
      var files = evt.target.files;
      if (files.length > 0) {
        this.cropParams = JSON.parse(JSON.stringify(this.cropParams)); //改变对象引用
        this.cropParams.src = files[0];
        this.cropParams.visible = true;
      }
      evt.target.value = "";
    },
    //裁剪回调
    cropCallback(e) {
      const vm = this;
      //给裁剪回显 赋值
      vm.imgUrl = Base64(e);

      // 判断返回Base64格式
      if (vm.format == "Base64") {
        vm.$emit("change", Base64(e));
      } else {
        // 判断返回Blob格式
        Blob(e).then((res) => {
          vm.$emit("change", res);
        });
      }
    },
    //选中的图片 准备进行裁剪
    uploadCallback(e) {
      // console.log(e);
    },
    //关闭弹出层
    closeCallback() {
      // console.log("关闭弹出层");
    },
  },
  mounted() {
    this.imgUrl = this.src;
  },
};
</script>
<style lang="scss" scoped>
@import "./modules/mobile.css";
@import "./font/iconfont.css";
.simple-crop-Wrap {
  width: 100%;
  height: 100%;
  .avatar {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: #aaa;
    display: flex;
    align-items: center;
    justify-content: center;
    input {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
      z-index: 2;
    }
    img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    .iconfont {
      color: #fff;
      font-size: 30px;
    }
  }
}
</style>